package com.webserver.core;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 处理与指定客户端的交互.
 * HTTP协议要求客户端与服务端的交互采取一问一答的原则
 * 因此交互流程分为三步
 * 1:解析请求(读取客户端发送过来的请求)
 * 2:处理请求
 * 3:发送响应
 */
public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    public void run() {
        try{
            //1解析请求
            HttpRequest request = new HttpRequest(socket);
            HttpResponse response = new HttpResponse(socket);

            //2处理请求
            //通过request获取浏览器请求的抽象路径
            String path = request.getUri();
            System.out.println("浏览器请求的抽象路径为:"+path);
            File file = new File("./webapps"+path);
            //判断该文件是否存在并且要求是一个文件才能响应
            if(file.exists()&&file.isFile()){
                System.out.println("资源已找到!");
                response.setEntity(file);
            }else{//如果资源不存在!
                System.out.println("资源不存在!");
                File notFound = new File("./webapps/root/404.notfound.html");
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                response.setEntity(notFound);
            }

            //3响应客户端
            response.flush();
            System.out.println("响应完毕!");
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                socket.close();//处理交互后与客户端断开连接
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}
